<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
         <label class="el-form-item-label">申请人</label>
        <el-select
          v-model="query.userId"
          clearable
          style="width: 185px;"
          placeholder="申请人"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option
            v-for="item in users"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
        <label class="el-form-item-label">订单号</label>
        <el-input
          v-model="query.no"
          clearable
          placeholder="订单号"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <label class="el-form-item-label">时间</label>
        <date-range-picker v-model="query.createdAt" class="date-item" />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="500px"
      >
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          size="small"
          label-width="80px"
        />
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button
            :loading="crud.status.cu === 2"
            type="primary"
            @click="crud.submitCU"
            >确认</el-button
          >
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%;"
        @selection-change="crud.selectionChangeHandler"
      >
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column prop="userName" label="申请人"  align="center"/>
        <el-table-column label="明细">
          <template slot-scope="scope">
            {{ getReagent(scope.row.store) }}
          </template>
        </el-table-column>
        <el-table-column prop="no" label="订单号"  align="center"/>
        <el-table-column prop="createdAt" label="时间"  align="center"/>
        <el-table-column prop="note" label="申请人备注"  align="center"/>
        <el-table-column prop="data" label="明细" width="100px" align="center">
          <template slot-scope="scope">
           <el-button type="primary" plain @click="showIngredientDialog(getReagent(scope.row.store))">查看成分</el-button>
          </template>
        </el-table-column>
        <el-table-column fixed="right"  width="150px" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              @click="handleAudit(scope.row, 0)"
              >拒绝</el-button
            >
            <el-button
              size="mini"
              type="success"
              @click="handleAudit(scope.row, 1)"
              >通过</el-button
            >
          </template>
        </el-table-column>
        <!-- <el-table-column v-if="checkPer(['admin','sensorLog:edit','sensorLog:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column> -->
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudHazardousChemicals,{searchId} from "@/api/hazardousChemicals";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import { storehouseOrderAudit } from "@/api/hazardousChemicals";
import { allNamelist } from "@/api/user";
import { mapState } from 'vuex'
import DateRangePicker from '@/components/DateRangePicker'

const defaultForm = {
  id: null,
  name: null,
  type: 2,
  amount: null,
  labId: null,
  note: null,
  createdAt: null,
  isDeleted: null,
  countType: null,
  updatedAt: null,
  barCode: null,
  cabinetId: null,
  measureId: 1,
  dangerClasses: null
};
export default {
  name: "Audit",
  components: { pagination, crudOperation, rrOperation, udOperation, DateRangePicker },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: "申领审核列表",
      url: "api/storehouseOrder/auditList",
      idField: "id",
      sort: "id,desc",
      crudMethod: { ...crudHazardousChemicals },
      optShow: {
        add: false,
        edit: false,
        del: false,
        download: true,
        reset: true
      }
    });
  },
  data() {
    return {
      reason: "",
      permission: {
        add: ["admin", "sensorLog:add"],
        edit: ["admin", "sensorLog:edit"],
        del: ["admin", "sensorLog:del"]
      },
      rules: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        // type: [
        //   { required: true, message: '危化品类型不能为空', trigger: 'blur' }
        // ],
        amount: [{ required: true, message: "数量不能为空", trigger: "blur" }],
        labId: [
          { required: true, message: "实验室不能为空", trigger: "change" }
        ],
        countType: [
          { required: true, message: "计数类型不能为空", trigger: "blur" }
        ],
        cabinetId: [
          { required: true, message: "试剂柜不能为空", trigger: "change" }
        ],
        // measureId: [
        //   { required: true, message: '计量方式不能为空', trigger: 'blur' }
        // ],
        dangerClasses: [
          { required: true, message: "危险等级不能为空", trigger: "blur" }
        ]
      },
      queryTypeOptions: [
        { key: "name", display_name: "名称" },
        // { key: 'type', display_name: '危化品类型' },
        { key: "labName", display_name: "实验室" },
        { key: "countType", display_name: "计数类型" },
        { key: "cabinetName", display_name: "试剂柜" },
        // { key: 'measureId', display_name: '计量方式' },
        { key: "dangerClasses", display_name: "危险等级" }
      ],
      users: [],
    };
  },
    created() {
    this.getUsers()
  },
  computed: {
    ...mapState('hjuser', ['systemSearchInfoId'])
  },
  methods: {
    showIngredientDialog(info){
      this.$alert(info, '明细', {
          confirmButtonText: '确定',
        });
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true;
    },
    async [CRUD.HOOK.afterRefresh]() {
      if (this.systemSearchInfoId) {
        try {
          const res = await searchId(this.systemSearchInfoId)
          this.crud.data = res.content
        } finally{
          this.$store.commit('hjuser/updatedsystemSearchInfoId', '')
        }
      }
      return true
    },
    dateFormat(picker) {
      if (picker == null) {
        this.form.createdAt = null;
        this.form.updatedAt = null;
      } else {
        this.form.createdAt = picker[0];
        this.form.updatedAt = picker[1];
      }
    },
    getUsers() {
      allNamelist()
        .then(response => {
          this.users = response.content
        })
        .catch(_ => {
          console.log(response)
        })
    },
    getReagent(data) {
      var text = "";
      data.forEach(item => {
        text +=
          item.name +
          "×" +
          item.num +
          (item.unit) +
          "、";
      });
      return text ? text.substring(0, text.length - 1) : "-";
    },
    handleAudit(row, status) {
      const text = status === 1 ? "通过" : "拒绝";
      this.$confirm("确定要" + text + row.userName + "的申请吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        var isInventory
        row.store.forEach(item =>{
          isInventory = item.inventory
        })
        if (status == 1 && isInventory == 1) {
          storehouseOrderAudit({ id: row.id, auditValue: status }).then(() => {
            this.crud.refresh();
          });
        }
        else if (status == 1 && isInventory == 0){
          this.$notify({
            type: 'warning',
            message: '库存不足，无法审核通过!',
            duration: 0
          });
        }
         else {
          this.$prompt("请输入拒绝理由：", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning", // 图标样式 "warning"|"error"...
            inputValue: "",
            inputErrorMessage: "拒绝理由不能为空",
            inputValidator: value => {
              // 点击按钮时，对文本框里面的值进行验证
              if (!value) {
                return "拒绝理由不能为空";
              }
              this.reason = value;
            }
          }).then(() => {
            storehouseOrderAudit({
              id: row.id,
              auditValue: status,
              note: this.reason
            }).then(() => {
              this.crud.refresh();
            });
          });
        }
      });
    }
  }
};
</script>

<style scoped></style>
